<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Book extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('welcome_message');
	}


	/**
	* @method list
	* @argument $pid 页码 默认为1
	* @return data 列表数据 
	*/
	public function list($pid)
	{
		/**
		* 校验pid为数字
		*/
		if(!preg_match('/^[1-9]\d*$/',$pid)){
			show_404('页面');
			exit;
		}

		//载入数据库
		$this->load->database();


		$offset=($pid-1)*10;
		//原生SQL查询
		//$query='SELECT uid,title,description,author,create_date,update_date FROM `book_item`  WHERE uid>=1  LIMIT '.$offset.',10';
		//使用CodeIginter内置数据库查询方法，简化查询语句
		$this->db->select('uid AS id,title,description,author,whole_name AS wholeName,create_date AS createTime,update_date AS updateTime');
		$data=$this->db->order_by('uid','DESC')->get('book_item', 10,$offset)->result();
		$recordCount=$this->db->count_all('book_item');
		$res=array('code'=>200,'info'=>'success','data'=>$data,'count'=>$recordCount);

		header('content-type:application/json;charset=utf-8');
		echo json_encode($res);

	}


	public function create(){
		//载入数据库
		$this->load->database();

		$JSON= file_get_contents("php://input");
		$input=json_decode($JSON);

		$title=$input->title;
		$description=$input->description;
		$chineseName=$input->chineseName;
		$englishName=$input->englishName;
		$wholeName=$input->wholeName;
		$author=$input->author;
		$categoryID=settype($input->category,'integer');
		$logo=$input->logo;
		$website=$input->website;
		$content=$input->content;
		//对tags 数组去重
		/*
		 * 思路：键值互换，通过array_keys直接获取键值
		*/
		$tags=array_keys(array_flip($input->tags));
		//ISO8601时间
		$createTime=date('c');


		//要执行的insert关联数组
		$insertData = array(
			'title' => $title,
			'description' => $description,
			'author' => $author,
			'chinese_name'=>$chineseName,
			'english_name'=>$englishName,
			'whole_name'=>$wholeName,
			'category_id'=>$categoryID,
			'logo'=>$logo,
			'website'=>$website,
			'create_date'=>$createTime,
			'content'=>$content
		);

		//生成insert sql
		$insertSQL = $this->db->insert_string('book_item', $insertData);

		$data=$this->db->query($insertSQL);
		
		$uid=$this->db->insert_id();
		
		$insertTagData=array();
		
		//要执行的insert关联数组
		foreach ($tags as $key => $value) {
			$insertTagData[$key]=array(
				'uid' => $uid,
				'tag_name'=>$value
			);
		}

		
		//批量插入
		$this->db->insert_batch('software_tag', $insertTagData);



		$res=array('code'=>200,'info'=>'success','data'=>$data,'uid'=>$uid);
		
		header('content-type:application/json;charset=utf-8');
		echo json_encode($res);

	}

	public function detail($pid){
		/**
		* 校验pid为数字
		*/
		if(!preg_match('/^[1-9]\d*$/',$pid)){
			show_404('页面');
			exit;
		}
		//载入数据库
		$this->load->database();


		//原生查询sql
		//$query='SELECT uid,title,description,author,create_date,update_date FROM `book_item`  WHERE uid='.$pid;
		//返回一行查询结果
		//$data=$this->db->query($query)->row();
		//使用CI内置查询，简化查询逻辑
		$this->db->select('uid AS id ,title,description,author,create_date AS createTime,update_date AS updateTime,chinese_name AS chineseName,english_name AS englishName,whole_name AS wholeName,category_id AS category,logo,website,content');
		$data=$this->db->get_where('book_item', array('uid' => $pid))->row_array();
		
		$this->db->select('tag_name AS tagName');
		$tags=$this->db->get_where('software_tag', array('uid' => $pid))->result_array();
		$tagNames=array_map(function($value){
			return $value['tagName'];
		},$tags);
		


		$data['platform']=isset($data['platform'])?$data['platform']:array();
		$data['tags']=$tagNames;

		

		$res=array('code'=>200,'info'=>'success','data'=>$data);


		

		header('content-type:application/json;charset=utf-8');
		echo json_encode($res);
	}

	public function search(){
		$keyword=$this->input->get('keyword');
		$page=intval($this->input->get('page'));
		//默认第一页
		$page=$page>1?$page:1;

		$offset=($page-1)*10;
		//载入数据库
		$this->load->database();
		

		//使用CodeIginter内置数据库查询方法，简化查询语句
		$this->db->select('uid AS id,title,description,author,whole_name AS wholeName,create_date AS createTime,update_date AS updateTime');
		$this->db->like('title', $keyword);
		$data=$this->db->get('book_item', 10,$offset)->result();

		$res=array('code'=>200,'info'=>'success','data'=>$data);
		
		header('content-type:application/json;charset=utf-8');
		echo json_encode($res);
	}

	public function update($uid){
		/**
		* 校验uid为数字
		*/
		if(!preg_match('/^[1-9]\d*$/',$uid)){
			show_404('页面');
			exit;
		}
		//载入数据库
		$this->load->database();

		$JSON= file_get_contents("php://input");
		$input=json_decode($JSON);
		
		
		$title=$input->title;
		$description=$input->description;
		$chineseName=$input->chineseName;
		$englishName=$input->englishName;
		$wholeName=$input->wholeName;
		$author=$input->author;
		$categoryID=$input->category;
		$logo=$input->logo;
		$website=$input->website;
		$content=$input->content;
		//ISO8601时间
		$updateTime=date('c');
		
		
		
		//要执行的update关联数组
		$updateData = array(
			'uid'=>$uid,
			'title' => $title,
			'description' => $description,
			'author' => $author,
			'chinese_name'=>$chineseName,
			'english_name'=>$englishName,
			'whole_name'=>$wholeName,
			'category_id'=>$categoryID,
			'logo'=>$logo,
			'website'=>$website,
			'update_date'=>$updateTime,
			'content'=>$content
		);
		
		

		//生成update sql
		
		$where = 'uid ='.$uid;
		
		$updateSQL = $this->db->update_string('book_item', $updateData,$where);
		
		
		
		$data=$this->db->query($updateSQL);
		
		
		
		$res=array('code'=>200,'info'=>'success','data'=>$data);

		header('content-type:application/json;charset=utf-8');
		echo json_encode($res);
		
	}
	
	//对象转数组
	public function object2array(&$object) {
		 $object =  json_decode(json_encode( $object),true);
		 return  $object;
	}



	//输出之前统一加上过滤器，自动替换为data-src的形式
	public function add_lazy_load_filter($html) {
		return preg_replace("/<img\s+src=\"([^\"]+)\"\s*\/?>/is", "<img data-src=\"\\1\">", $html);
	}

	//在获取存储的正文之后用正则表达式批量替换内容
	public function imgLazyLoad($content){
		$content = $content.replaceAll("<img(.*?)src=(.*?)>","<img$1 class='lazy' data-original=$2>");
	}


}
